package ms.platform.system.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import ms.platform.system.model.AdminRole;
import ms.platform.system.model.Resource;
import ms.platform.system.model.Role;
import ms.platform.system.service.ResourceService;
import ms.platform.system.service.RoleService;
import ms.platform.util.PageUtils;

@Controller
@RequestMapping("/system/role/")
public class RoleController extends BaseController{

	@Autowired
	private RoleService roleService;
	
	@Autowired
	private ResourceService resourceService;
	
	
	/**
	 * 角色列表
	 * @param map
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/list")
	public String list(@RequestParam Map<String,Object> map, HttpServletRequest request){
		map.put("count", roleService.queryRoleCount(map));
		List<Role> list = roleService.queryRoleListByCondition(PageUtils.Page(request,map));
		request.setAttribute("list", list);
		PageUtils.calculate(map);
		List<Resource> resourceList = resourceService.queryResourceList();
		request.setAttribute("resourceList", resourceList);
		PageUtils.calculate(map);
		return "system/role/list";
	}
	
	/**
	 * 跳转角色编辑页面
	 * @param id
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/toEdit")
	public String toEdit(Integer id, HttpServletRequest request){
		if(id!= null){
			Role role = roleService.queryRoleById(id);
			request.setAttribute("role", role);
		}
		return "system/role/edit";
	}
	
	
	/**
	 * 跳转角色添加页面
	 * @param id
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/toAddRole")
	public String toAddRole(Integer id, HttpServletRequest request){
		return "system/role/add";
	}
	
	/**
	 * 添加角色
	 * @param role
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/save")
	@ResponseBody
	public Object save(Role role, HttpServletRequest request){
		roleService.insert(role);
		return returnSuccess("操作成功", role);
	}
	
	/**
	 * 修改角色
	 * @param role
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/editRole")
	@ResponseBody
	public Object editRole(Role role, HttpServletRequest request){
		 
		Role roler = roleService.queryRoleByName(role.getRoleName());
		if(roler==null && role.getId()!=null){
			roleService.update(role);
			return returnSuccess("操作成功", role);
		}else if(roler!=null && roler.getId()==role.getId()){
			roleService.update(role);
			return returnSuccess("操作成功", role);
		}else{
			return returnError(1,"该角色名已存在，请重新填写", role);
		}
	}
	
	/**
	 * 禁用角色
	 * @param role
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/disabledRole")
	@ResponseBody
	public Object disabledRole(Role role, HttpServletRequest request){
		roleService.update(role);
		return returnSuccess("操作成功",role.getId());
	}
	
	/**
	 * 检查角色是否已经存在
	 * @param role
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/getRoleByName")
	@ResponseBody
	public Object getRoleByName(String roleName, HttpServletRequest request){
		boolean result = true;
		Role role = roleService.queryRoleByName(roleName.trim());
		if(role != null){
			result = false;
		}
		Map<String, Boolean> map = new HashMap<>();
        map.put("valid", result);
		 ObjectMapper mapper = new ObjectMapper();
	        String resultString = "";
	        try {
	            resultString = mapper.writeValueAsString(map);
	        } catch (JsonProcessingException e) {
	            e.printStackTrace();
	        } catch (IOException e) {
				e.printStackTrace();
			}
	        return resultString;
	}
	
	/**
	 * 删除角色
	 * @param roleId
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/deleteRole")
	@ResponseBody
	public Object deleteRole(Integer roleId, HttpServletRequest request){
		roleService.deleteById(roleId);
		resourceService.deleteRoleResourceById(roleId);
		return returnSuccess("操作成功",roleId);
	}
	
	
	/**
	 * 跳转到分配角色页面
	 * @param id
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/toAllotRole")
	@ResponseBody
	public Object toAllotRole(Integer id, HttpServletRequest request){
		List<Role> roleList = roleService.getAllRoleByAdminId(id);
		String roleIds="";
		for (Role role:roleList) {
			roleIds+=role.getId()+",";
		}
		return returnSuccess("返回信息成功", roleIds);
	}
	
	/**
	 * 分配角色
	 * @param ar
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/allotRole")
	@ResponseBody
	public Object allotRole(AdminRole ar,HttpServletRequest request){
		if(ar!=null && ar.getRoleIds()!=null){ 
			String[] ayy=ar.getRoleIds().split(",");
			for (int i = 0; i < ayy.length; i++) {
				String[] r=ayy[i].split("-");
				Integer type=Integer.valueOf(r[1]);
				Integer id=Integer.valueOf(r[0]);
				ar.setRoleId(id);
				//分配角色
				if(type==1){
					//分配角色
					if(this.roleService.queryAdminRole(ar)==null){
						this.roleService.insertAdminRole(ar);
					}
				}else if(type==0){
					//删除分配
					this.roleService.deleteAdminRole(ar);
				}
			}
			
		}
		return returnSuccess("操作成功", null);
	}
	
	
	
}
